const Koa = require('koa')
const views = require('koa-views')
const Router = require('@koa/router')
const koaBody = require('koa-body')
const path = require('path')
const userDb = require('./db')
const md5 = require('md5')

const app = new Koa()

app.context.db = {
    user: userDb
}
app.use((views(path.join(__dirname, './public'))))
app.use(koaBody())

const userRouter = new Router()

userRouter.get('/', async (ctx) => {
    await ctx.render('index')
})
userRouter.get('/register', async (ctx) => {
    await ctx.render('register')
})

userRouter.post('/register', async (ctx) => {
    const { username, password } = ctx.request.body
    let result = {
        success: true,
        msg: '',
        data: {
            user: {
                
            }
        }
    }

    let res = await ctx.db.user.create({
        username, password
    })
    result.data.user = res

    // ctx.body = result
    ctx.redirect('/?register=true')
})

userRouter.post('/login', async (ctx) => {
    const { username, password } = ctx.request.body
    let result = {
        success: true,
        msg: '',
        data: {
            user: {}
        }
    }

    let res = await ctx.db.user.findAll({
        where: {
            username,
            password: md5(password)
        }
    })
    if (res.length > 0) {
        result = {
            success: true,
            msg: '',
            data: {
                user: res[0]
            }
        }
    } else {
        result = {
            success: false,
            msg: '登录失败, 账号或密码错误',
            data: {
                user: {}
            }
        }
    }

    ctx.body = result
})

app.use(userRouter.routes())

app.listen(80, () => {
    console.log('server is runging')
})
